<template>
  <div class="space-y-4">
    <!-- 根据提供商动态生成表单字段 -->
    <div v-for="field in formFields" :key="field.key" class="space-y-1">
      <label class="block text-sm font-medium text-gray-700 mb-1">{{ field.label }}</label>
      <input
        :type="field.type"
        :value="providerConfig[field.key]"
        @input="updateField(field.key, $event)"
        :placeholder="field.label"
        class="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
      />
    </div>

    <!-- 保存按钮 -->
    <div class="flex justify-end mt-4">
      <button
        @click="saveConfig"
        class="px-4 py-2 bg-indigo-600 border border-transparent rounded-md text-white hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
      >
        保存配置
      </button>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, computed, onMounted, watch } from 'vue'
  import useProviderConfigStore from '../store/modules/providerConfigStore'

  // 组件属性
  interface Props {
    providerName: string
  }

  const props = defineProps<Props>()
  const emit = defineEmits(['saved'])

  // 获取配置store
  const configStore = useProviderConfigStore()

  // 初始化store
  onMounted(() => {
    configStore.initConfig()
  })

  // 当前提供商的配置
  const providerConfig = ref<Record<string, string>>({})

  // 监听提供商变化，更新表单数据
  watch(
    () => props.providerName,
    newName => {
      if (newName) {
        providerConfig.value = { ...configStore.getConfig(newName) }
      }
    },
    { immediate: true }
  )

  // 获取当前提供商的表单字段
  const formFields = computed(() => {
    return configStore.getFormFields(props.providerName)
  })

  // 更新字段值
  const updateField = (key: string, event: Event) => {
    const target = event.target as HTMLInputElement
    providerConfig.value[key] = target.value
  }

  // 保存配置
  const saveConfig = () => {
    configStore.updateConfig(props.providerName, providerConfig.value)
    emit('saved')
  }
</script>
